/*
 *    Copyright (c) 2018-2025, cloud All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: cloud
 */
package com.fuyao.cloud.personnel.problem.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fuyao.cloud.admin.api.utils.NumberUtils;
import com.fuyao.cloud.common.core.exception.IdIsNullException;
import com.fuyao.cloud.common.core.util.R;
import com.fuyao.cloud.common.data.datascope.DataScope;
import com.fuyao.cloud.common.excel.vo.ErrorMessage;
import com.fuyao.cloud.personnel.api.constant.CommonConstants;
import com.fuyao.cloud.personnel.api.constant.TenderConstants;
import com.fuyao.cloud.personnel.api.entity.TenderBasicSituation;
import com.fuyao.cloud.personnel.api.entity.TenderSupervision;
import com.fuyao.cloud.personnel.api.vo.TenderSupperviBasicVO;
import com.fuyao.cloud.personnel.api.vo.excel.NonPubTenderExcelVO;
import com.fuyao.cloud.personnel.api.vo.excel.PubTenderExcelVO;
import com.fuyao.cloud.personnel.problem.mapper.TenderBasicSituationMapper;
import com.fuyao.cloud.personnel.problem.mapper.TenderSupervisionMapper;
import com.fuyao.cloud.personnel.problem.service.TenderSupervisionService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 招标表
 *
 * @author hyc
 * @date 2022-05-20 10:52:12
 */
@Service
public class TenderSupervisionServiceImpl extends ServiceImpl<TenderSupervisionMapper, TenderSupervision> implements TenderSupervisionService {

    @Autowired
    private TenderBasicSituationMapper tenderBasicSituationMapper;

    @Override
    public <E extends IPage<TenderSupervision>> E page(E page, Wrapper<TenderSupervision> queryWrapper) {
        return this.baseMapper.selectPageByScope(page,queryWrapper,new DataScope());
    }

    @Override
    public boolean save(TenderSupervision entity) {
        String onlyNum = "";
        TenderSupervision tenderSupervision = this.baseMapper.selectOne(Wrappers.<TenderSupervision>lambdaQuery().eq(TenderSupervision::getTenderType,entity.getTenderType()).orderByDesc(TenderSupervision::getId).last("LIMIT 1"));
        if (tenderSupervision!=null) {
            if (entity.getTenderType().equals(TenderConstants.PUBLIC_TENDER_TYPE)){
                onlyNum = TenderConstants.PUBLIC_TENDER+ DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN)+NumberUtils.getIncrementNum(tenderSupervision.getNumber().substring(10));
            }else if (entity.getTenderType().equals(TenderConstants.NON_PUBLIC_TENDER_TYPE)){
                onlyNum = TenderConstants.NON_PUBLIC_TENDER+ DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN)+NumberUtils.getIncrementNum(tenderSupervision.getNumber().substring(11));
            }
        }else {
            if (entity.getTenderType().equals(TenderConstants.PUBLIC_TENDER_TYPE)){
                onlyNum = TenderConstants.PUBLIC_TENDER+ DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN) + CommonConstants.DEFAULT_NUMBER_SUFFIX;
            }else if (entity.getTenderType().equals(TenderConstants.NON_PUBLIC_TENDER_TYPE)){
                onlyNum = TenderConstants.NON_PUBLIC_TENDER+ DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN) + CommonConstants.DEFAULT_NUMBER_SUFFIX;
            }
        }
        entity.setNumber(onlyNum);
        return super.save(entity);
    }

    @Override
    @Transactional(rollbackFor = IdIsNullException.class)
    public Boolean saveTenderSupperviBasicVO(TenderSupperviBasicVO tenderSupperviBasicVO) {
        TenderSupervision tenderSupervision =new TenderSupervision();
        BeanUtils.copyProperties(tenderSupperviBasicVO,tenderSupervision);
        this.save(tenderSupervision);
        if (tenderSupervision.getId() != null && tenderSupervision.getId() > 0){
            List<TenderBasicSituation> tenderBasicSituationList = tenderSupperviBasicVO.getTenderBasicSituationList();
            for (int i = 0; i < tenderBasicSituationList.size(); i++) {
                TenderBasicSituation tenderBasicSituation = tenderBasicSituationList.get(i);
                tenderBasicSituation.setTenderSupervisionId(tenderSupervision.getId());
            }
            this.tenderBasicSituationMapper.insertBatchSomeColumn(tenderBasicSituationList);
            return true;
        }else {
            throw new IdIsNullException("id为null");
        }
    }

    @Override
    public R importPubTender(List<PubTenderExcelVO> excelVOList, BindingResult bindingResult) {
        // 通用校验获取失败的数据
        List<ErrorMessage> errorMessageList = (List<ErrorMessage>) bindingResult.getTarget();

        for (int i = 0; i < excelVOList.size(); i++) {
            PubTenderExcelVO pubTenderExcelVO = excelVOList.get(i);
            Set<String> errorMsg = new HashSet<>();

            // 数据合法情况
            if (CollUtil.isEmpty(errorMsg)) {
                insertExcelPubTender(pubTenderExcelVO);
            }
            else {
                // 数据不合法情况
                errorMessageList.add(new ErrorMessage((long) (i + 2), errorMsg));
            }
        }

        if (CollUtil.isNotEmpty(errorMessageList)) {
            return R.failed(errorMessageList);
        }

        return R.ok();
    }

    private void insertExcelPubTender(PubTenderExcelVO pubTenderExcelVO) {
        TenderSupervision tenderSupervision =new TenderSupervision();
        BeanUtils.copyProperties(tenderSupervision,pubTenderExcelVO);
        super.save(tenderSupervision);
    }

    @Override
    public R importNonPubTender(List<NonPubTenderExcelVO> excelVOList, BindingResult bindingResult) {
        // 通用校验获取失败的数据
        List<ErrorMessage> errorMessageList = (List<ErrorMessage>) bindingResult.getTarget();

        for (int i = 0; i < excelVOList.size(); i++) {
            NonPubTenderExcelVO nonPubTenderExcelVO = excelVOList.get(i);
            Set<String> errorMsg = new HashSet<>();

            // 数据合法情况
            if (CollUtil.isEmpty(errorMsg)) {
                insertExcelNonPubTender(nonPubTenderExcelVO);
            }
            else {
                // 数据不合法情况
                errorMessageList.add(new ErrorMessage((long) (i + 2), errorMsg));
            }
        }

        if (CollUtil.isNotEmpty(errorMessageList)) {
            return R.failed(errorMessageList);
        }

        return R.ok();
    }

    private void insertExcelNonPubTender(NonPubTenderExcelVO nonPubTenderExcelVO) {
        TenderSupervision tenderSupervision =new TenderSupervision();
        BeanUtils.copyProperties(tenderSupervision,nonPubTenderExcelVO);
        super.save(tenderSupervision);
    }
}
